/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UsuariosAgregarFrame.java
 *
 * Created on 03/04/2009, 10:20:22 AM
 */

package org.general.usuarios;

import org.mybeans.Sesion;
import org.mybeans.GruposUsuariosBeans;
import org.mybeans.UsuariosBeans;
import org.general.utilidades.Encriptador;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author avbravo
 */
public class UsuariosAgregarFrame extends javax.swing.JFrame {
Sesion sesion;
UsuariosBeans usuariosBeans;
GruposUsuariosBeans gruposUsuariosBeans;
    Encriptador encrypter;

    /** Create new form UsuariosAgregarFrame */
    public UsuariosAgregarFrame() {
        initComponents();
        sesion =new Sesion();
        usuariosBeans = new UsuariosBeans();
        gruposUsuariosBeans = new GruposUsuariosBeans();
        encrypter = new Encriptador();
                /*
       * Fondo
       */

		 
		 
		 

		jXPanel1.setOpaque(false);
		setContentPane(jXPanel1 );
/*
 * fondo
 */
        CargarGruposUsuarios();
        AutoCompleteDecorator.decorate(this.jComboBoxGrupoUsuario);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jXPanel1 = new org.jdesktop.swingx.JXPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldUsername = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jPasswordField = new javax.swing.JPasswordField();
        jPasswordFieldRepetido = new javax.swing.JPasswordField();
        jTextFieldUsuario = new javax.swing.JTextField();
        jTextFieldCedula = new javax.swing.JTextField();
        jComboBoxGrupoUsuario = new javax.swing.JComboBox();
        jTextFieldTelefono = new javax.swing.JTextField();
        jTextFieldCelular = new javax.swing.JTextField();
        jTextFieldEmail = new javax.swing.JTextField();
        jButtonCerrar = new javax.swing.JButton();
        jButtonGuardar = new javax.swing.JButton();
        jButtonLimpiar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("AGREGAR USUARIOS");

        jLabel1.setText("Username");

        jLabel2.setText("Password");

        jLabel3.setText("Repetir Password");

        jLabel4.setText("Nombre Completo");

        jLabel5.setText("Email");

        jLabel6.setText("Telefono");

        jLabel7.setText("Celular");

        jLabel8.setText("Cedula");

        jLabel9.setText("Grupo Usuario");

        jComboBoxGrupoUsuario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBoxGrupoUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxGrupoUsuarioActionPerformed(evt);
            }
        });

        jButtonCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonCerrar.setToolTipText("Regresar");
        jButtonCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCerrarActionPerformed(evt);
            }
        });

        jButtonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/save.png"))); // NOI18N
        jButtonGuardar.setToolTipText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/escoba.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jXPanel1Layout = new javax.swing.GroupLayout(jXPanel1);
        jXPanel1.setLayout(jXPanel1Layout);
        jXPanel1Layout.setHorizontalGroup(
            jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel8)
                    .addComponent(jLabel9)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addGroup(jXPanel1Layout.createSequentialGroup()
                        .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(53, 53, 53)
                        .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jPasswordFieldRepetido, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jPasswordField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE))
                            .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextFieldUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jXPanel1Layout.createSequentialGroup()
                                .addComponent(jTextFieldTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel7)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldCelular, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE))
                            .addComponent(jComboBoxGrupoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jXPanel1Layout.createSequentialGroup()
                                .addComponent(jButtonGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                                .addGap(18, 18, 18)
                                .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jXPanel1Layout.setVerticalGroup(
            jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jPasswordFieldRepetido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(jComboBoxGrupoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jXPanel1Layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel5))
                    .addGroup(jXPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7)
                            .addComponent(jTextFieldCelular, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(jButtonCerrar, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(jButtonLimpiar, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jXPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jXPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCerrarActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_jButtonCerrarActionPerformed

    private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
        // TODO add your handling code here:
         try {
 String username = this.jTextFieldUsername.getText();
        if (username == null || username.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el username ", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldUsername.requestFocus();
            return;
        }
    String password = new String(this.jPasswordField.getPassword());

        if (password == null || password.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el password del usuario", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jPasswordField.requestFocus(); 
            return;
        }
        String passwordRepetido = new String(this.jPasswordFieldRepetido.getPassword());

        if (passwordRepetido == null || passwordRepetido.equals("")) {
            JOptionPane.showMessageDialog(this, "Por favor repita el password", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jPasswordField.requestFocus();
            return;
        }
        if (passwordRepetido.equals(password) == false) {
            JOptionPane.showMessageDialog(this, "No coinciden los password", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jPasswordField.requestFocus();
            return;
        }
        
        password = encrypter.encrypt(password);
       String usuario = this.jTextFieldUsuario.getText();
        if (usuario == null || usuario.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el nombre del usuario ", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldUsuario.requestFocus();
            return;
        }

        String cedula = this.jTextFieldCedula.getText();
        if (cedula == null || cedula.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese la cedula ", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldCedula.requestFocus();
            return;
        }

        
        String GrupoUsuario = (String) this.jComboBoxGrupoUsuario.getSelectedItem();
        if (GrupoUsuario == null || GrupoUsuario.equals("")) {
            JOptionPane.showMessageDialog(this, "seleccione un grupo de usuario", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String idgrupousuario = gruposUsuariosBeans.BuscarIdGruposUsuarios(GrupoUsuario);
        if (idgrupousuario.equals("")){
             JOptionPane.showMessageDialog(this, "seleccione un grupo de usuario", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String telefono = this.jTextFieldTelefono.getText();
        String celular = this.jTextFieldCelular.getText();
        String email = this.jTextFieldEmail.getText();
        
        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String sqlquery = "select * from usuarios where idmunicipio = ? and username =?";
        PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
        psquery.setString(1, sesion.getIdmunicipio());
        psquery.setString(2, username);
        ResultSet rs = psquery.executeQuery();
        rs.next();
        int x = rs.getRow();

        if (x != 0) {
            JOptionPane.showMessageDialog(this, "Existe un usuario con ese username", "Mensaje", JOptionPane.INFORMATION_MESSAGE);

            return;
        }

        String sql = "INSERT into usuarios VALUES(?,?,?,?,?,?,?,?,?,?)";
        PreparedStatement prest = sesion.con.prepareStatement(sql);

        prest.setString(1, username);
        prest.setString(2, password);
        prest.setString(3, usuario);
        prest.setString(4, sesion.getIdmunicipio());
        prest.setString(5, email);
        prest.setString(6, telefono);
        prest.setString(7, celular);
        prest.setString(8, "si"); //activo
        prest.setString(9, idgrupousuario);
        prest.setString(10, cedula);
        
        
        int count = prest.executeUpdate();
        sesion.con.close();
        JOptionPane.showMessageDialog(this, "Usuario Guardado exitosamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
        
    } catch (Exception ex) {
    
        JOptionPane.showMessageDialog(this, "Clase:UsuariosAgregarFrame.java\nMetodo:jButtonGuardarActionPerformed()\nError " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
    }//GEN-LAST:event_jButtonGuardarActionPerformed

    private void jComboBoxGrupoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxGrupoUsuarioActionPerformed
        // TODO add your handling code here:

    }//GEN-LAST:event_jComboBoxGrupoUsuarioActionPerformed

    private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed
        // TODO add your handling code here:
         this.jTextFieldUsername.setText("");

    this.jPasswordField.setText("");

        this.jPasswordFieldRepetido.setText("");

 this.jTextFieldUsuario.setText("");
 this.jTextFieldCedula.setText("");
 this.jComboBoxGrupoUsuario.setSelectedItem("");
this.jTextFieldTelefono.setText("");
this.jTextFieldCelular.getText();
this.jTextFieldEmail.setText("");
this.jTextFieldUsername.requestFocus();
    }//GEN-LAST:event_jButtonLimpiarActionPerformed

private void CargarGruposUsuarios(){
 try {
        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
         }
            String sqlquery = "select *  from gruposusuarios where activo='si' and idgrupousuario <>'desarrollador' order by grupousuario";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            ResultSet rs = psquery.executeQuery();
            jComboBoxGrupoUsuario.removeAllItems();
            int count = 0;
            while (rs.next()) {
               String grupousuario = rs.getString("grupousuario");
               jComboBoxGrupoUsuario.insertItemAt(grupousuario, count);
                count++;
            }
            sesion.con.close();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Clase:UsuariosAgregarFrame.java\nMetodo: CargarGruposUsuarios()\nError:" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

    }



    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UsuariosAgregarFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCerrar;
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JComboBox jComboBoxGrupoUsuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPasswordField jPasswordField;
    private javax.swing.JPasswordField jPasswordFieldRepetido;
    private javax.swing.JTextField jTextFieldCedula;
    private javax.swing.JTextField jTextFieldCelular;
    private javax.swing.JTextField jTextFieldEmail;
    private javax.swing.JTextField jTextFieldTelefono;
    private javax.swing.JTextField jTextFieldUsername;
    private javax.swing.JTextField jTextFieldUsuario;
    private org.jdesktop.swingx.JXPanel jXPanel1;
    // End of variables declaration//GEN-END:variables

}
